Highlight Keywords in Search Results using PHP and MySql

Highlight Keywords in Search Results using PHP and MySql

If you are a php programmer then this article will very helpful in your career. Highlight your keyword in your searching results which will help your user to identify the more appropriate records. As you know Searching Functionality is very useful feature to find relevant data quickly from the database records. Highlight Keyword feature makes the search functionality more user-friendly.

In Search terms, this feature will give you option to change the keywords background color or text color with different colors in search records. In this tutorials, i will show you how to fetch records from database and highlight keywords in search results using PHP and MySql.

Highlight Keywords in records

The highlight_keywords() is a custom defined function that will use to highlight the words in search results.

  • The explode() function is used to convert keyword string into array of each word.
  • The PHP str_ireplace() function is used to replace and highlight the each matched word .

For this example, First we will create a “posts” table with some fields like id, title, content,created_on in database. This table will holds the multiple records which will be use to search records and highlight searching keywords.

Database Configuration file (dbConfig.php)

index.php file with HTML Search form

HTML Form will help to search keyword string. After submit form the input keyword will pass using post method to search_result.php file.

search_result.php file

In this file, we will receive submit keyword value and search the records from database.

The Where clause is used to filter the records from database using LIKE operator.

Before displaying the search records, the highlight_keywords() function is used to add the highlight inline css in the matched words.

When the keywords are wrapped with highlight the word in the search records, then the attached inline css is used to highlight the string with background color (As per your inline css properties).

Highlight Keywords with CSS

You can also use class instead of inline css to highlight keyword in records. In this case, the highlight_keywords() will be modified like the following code:

Related posts